import mysql
from PyQt5.QtCore import pyqtSignal, QObject
from mysql.connector import Error
from Manage.db_connector import DBUtils


class CustomerManager(QObject):  # 继承自 QObject
    """客户管理类 - 继承自 QObject 以支持信号"""

    # 添加客户变更信号
    customerChanged = pyqtSignal()

    def __init__(self, parent=None):
        super().__init__(parent)  # 调用父类 QObject 的构造函数
        self.db = DBUtils()
        self.db.connect()

    def __del__(self):
        """析构函数，在对象销毁时自动关闭数据库连接"""
        try:
            self.db.disconnect()
        except Exception:
            pass
        super().__del__() if hasattr(super(), '__del__') else None

    def is_phone_unique(self, phone, exclude_id=None):
        """
        检查电话号码是否唯一
        :param phone: 要检查的电话号码
        :param exclude_id: 要排除的客户ID（用于编辑时排除自己）
        :return: 如果唯一返回True，否则返回False
        """
        try:
            # 准备查询参数
            query = "SELECT COUNT(*) as count FROM userinfo WHERE telephone = %s"
            params = (phone,)

            # 添加排除ID条件
            if exclude_id is not None:
                query += " AND customerID != %s"
                params = (phone, exclude_id)

            # 使用 DBUtils 执行查询
            result = self.db.execute_query(query, params)

            # 检查结果是否有效
            if not result or not isinstance(result, list) or len(result) == 0:
                print(f"查询电话 {phone} 未返回结果")
                return False

            # 获取计数
            count = result[0].get('count', 0)
            return count == 0

        except Exception as e:
            print(f"检查电话号码唯一性时发生异常: {e}")
            return False

    def add_customer(self, customername, pid, telephone, address=None):
        """向userInfo表增加新客户（带电话号码唯一性检查）"""
        # 先检查电话号码唯一性
        if not self.is_phone_unique(telephone):
            print(f"手机号 {telephone} 已被使用")
            return False

        query = """
        INSERT INTO userInfo (customerName, PID, telephone, address)
        VALUES (%s, %s, %s, %s)
        """
        params = (customername, pid, telephone, address)
        result = self.db.execute_query(query, params, fetch=False)

        if result:
            print(f"成功添加客户: {customername}")
            self.customerChanged.emit()  # 通知UI刷新
            return True
        return False

    def update_customer(self, customer_id, customername=None, pid=None, telephone=None, address=None):
        """更新客户信息（带电话号码唯一性检查）"""
        # 获取当前客户信息
        current_customer = self.get_customer_by_id(customer_id)
        if not current_customer:
            print(f"找不到客户ID {customer_id}")
            return False

        # 如果电话号码变更，检查新号码唯一性
        if telephone and telephone != current_customer.get('telephone'):
            if not self.is_phone_unique(telephone, exclude_id=customer_id):
                print(f"手机号 {telephone} 已被其他客户使用")
                return False

        # 构建动态更新语句
        updates = []
        params = []

        # 检查哪些字段需要更新
        if customername:
            updates.append("customerName = %s")
            params.append(customername)
        if pid:
            updates.append("PID = %s")
            params.append(pid)
        if telephone:
            updates.append("telephone = %s")
            params.append(telephone)
        if address:
            updates.append("address = %s")
            params.append(address)

        if not updates:
            print("没有提供更新字段")
            return False

        query = f"UPDATE userInfo SET {', '.join(updates)} WHERE customerID = %s"
        params.append(customer_id)

        result = self.db.execute_query(query, params, fetch=False)
        if result:
            print(f"成功更新客户ID {customer_id} 的信息")
            self.customerChanged.emit()  # 通知UI刷新
            return True
        return False

    def delete_customer(self, customerid):
        """删除客户信息 - 增强版"""
        customer = self.get_customer_by_id(customerid)
        if not customer:
            print(f"错误: 客户ID {customerid} 不存在")
            return False

        # 重置数据库连接以确保最新数据
        self.db.reset_connection()

        # 检查客户是否有银行卡 - 使用新连接确保实时数据
        check_query = "SELECT COUNT(*) as count FROM cardInfo WHERE customerID = %s"
        check_result = self.db.execute_query(check_query, (customerid,))

        # 处理结果
        count = 0
        if check_result and check_result[0]:
            first_result = check_result[0]
            if isinstance(first_result, dict) and 'count' in first_result:
                count = first_result['count']
            elif isinstance(first_result, tuple) and len(first_result) > 0:
                count = first_result[0]
            elif isinstance(first_result, list) and len(first_result) > 0:
                count = first_result[0]

        if count > 0:
            # 获取银行卡列表
            cards_query = "SELECT cardID FROM cardInfo WHERE customerID = %s"
            cards = self.db.execute_query(cards_query, (customerid,))
            card_ids = [card['cardID'] for card in cards] if cards else []

            # 显示详细错误信息
            error_msg = (
                f"该客户有关联的银行卡，请先删除银行卡\n\n"
                f"关联银行卡ID: {', '.join(card_ids[:5])}{'...' if len(card_ids) > 5 else ''}"
            )
            print(error_msg)
            return False

        # 执行删除
        query = "DELETE FROM userInfo WHERE customerID = %s"
        result = self.db.execute_query(query, (customerid,), fetch=False)

        if result:
            print(f"成功删除客户ID {customerid}")
            self.customerChanged.emit()  # 通知UI刷新
            return True

        return False

    def get_customer_by_id(self, customerid):
        """获取单个客户信息"""
        query = "SELECT * FROM userInfo WHERE customerID = %s"
        result = self.db.execute_query(query, (customerid,))
        return result[0] if result else None

    def list_all_customers(self):
        """获取所有客户信息"""
        query = "SELECT * FROM userInfo ORDER BY customerID"
        return self.db.execute_query(query)

